package goods.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import common.model.goods.Comment;
import common.model.result.Result;
import common.model.result.ResultCodeEnum;
import common.dto.goodsdto.CommentDTO;
import common.dto.goodsdto.CommentUser;
import common.dto.goodsdto.SpuVO;
import goods.mapper.CommentMapper;
import goods.service.ICommentService;
import goods.service.IGoodsService;
import goods.service.UserServiceFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.beans.BeanUtils;
import com.alibaba.fastjson.JSON;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.time.LocalDateTime;

@Service
public class CommentServiceImpl implements ICommentService {

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private UserServiceFeignClient userServiceFeignClient;
    
    @Autowired
    private IGoodsService goodsService;

    //添加评论
    @Override
    public Result addComment(Comment comment) {
        // 验证必要字段
        if (comment == null || comment.getSpuId() == null || comment.getUserId() == null || 
            comment.getOrderId() == null || comment.getContent() == null) {
            return Result.failure(ResultCodeEnum.FAIL, "评论信息不完整");
        }
        
        // 设置默认值
        // comment.setStatus(0); // 待审核状态
        comment.setStatus(1); // 已发布状态
        comment.setCreatedAt(LocalDateTime.now());
        
        // 处理imageUrls字段，确保它是有效的JSON格式
        if (comment.getImageUrls() != null && (comment.getImageUrls().isEmpty() || 
            "[]".equals(comment.getImageUrls()) || "{}".equals(comment.getImageUrls()))) {
            comment.setImageUrls("[]"); // 设置为空数组
        }
        comment.setId(null);//防止MybatisPlus自动生成id
        commentMapper.insert(comment);
        return Result.success("评论添加成功");
    }

    //根据商品id查询评论
    @Override
    public Result getCommentsBySpuId(Long spuId, Integer page, Integer pageSize) {
        if (spuId == null) {
            return Result.failure(ResultCodeEnum.FAIL, "商品ID不能为空");
        }
        
        // 构建查询条件
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Comment::getSpuId, spuId)
                    .eq(Comment::getStatus, 1) // 只查询已发布的评论
                    .orderByDesc(Comment::getCreatedAt);
        
        // 分页查询
        Page<Comment> commentPage = new Page<>(page, pageSize);
        Page<Comment> resultPage = commentMapper.selectPage(commentPage, queryWrapper);
        
        // 将Comment转换为CommentDTO，并添加用户信息
        List<CommentDTO> commentDTOList = new ArrayList<>();
        for (Comment comment : resultPage.getRecords()) {
            CommentDTO commentDTO = new CommentDTO();
            BeanUtils.copyProperties(comment, commentDTO);
            
            // 将JSON格式的imageUrls转换为List<String>
            if (comment.getImageUrls() != null && !comment.getImageUrls().isEmpty()) {
                try {
                    List<String> imageUrlList = JSON.parseArray(comment.getImageUrls(), String.class);
                    commentDTO.setImageUrls(imageUrlList);
                } catch (Exception e) {
                    // 解析失败时设置为空列表
                    commentDTO.setImageUrls(new ArrayList<>());
                }
            } else {
                commentDTO.setImageUrls(new ArrayList<>());
            }
            
            // 获取用户信息
            if (comment.getUserId() != null) {
                Result userResult = userServiceFeignClient.getUserById(comment.getUserId());
                if (userResult != null && userResult.getData() != null) {
                    Map<String, Object> userData = (Map<String, Object>) userResult.getData();
                    commentDTO.setUserName((String) userData.get("nickName"));
                    commentDTO.setUserIcon((String) userData.get("icon"));
                    commentDTO.setCreatedAt(comment.getCreatedAt());
                    commentDTO.setUpdatedAt(comment.getUpdatedAt()); 
                }
            }
            
            commentDTOList.add(commentDTO);
        }
        
        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("total", resultPage.getTotal());
        result.put("pages", resultPage.getPages());
        result.put("current", resultPage.getCurrent());
        result.put("size", resultPage.getSize());
        result.put("records", commentDTOList);
        
        return Result.success(result);
    }
    //根据用户id查询我的评论列表
    @Override
    public Result getCommentsByUserId(Long userId, Integer page, Integer pageSize) {
        if (userId == null) {
            return Result.failure(ResultCodeEnum.FAIL, "用户ID不能为空");
        }
        
        // 构建查询条件
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Comment::getUserId, userId)
                    .eq(Comment::getStatus, 1) // 只查询已发布的评论
                    .orderByDesc(Comment::getCreatedAt);
        
        // 分页查询
        Page<Comment> commentPage = new Page<>(page, pageSize);
        Page<Comment> resultPage = commentMapper.selectPage(commentPage, queryWrapper);
        
        // 将Comment转换为CommentUser，并添加商品信息
        List<CommentUser> commentUserList = new ArrayList<>();
        for (Comment comment : resultPage.getRecords()) {
            CommentUser commentUser = new CommentUser();
            BeanUtils.copyProperties(comment, commentUser);
            
            // 将JSON格式的imageUrls转换为List<String>
            if (comment.getImageUrls() != null && !comment.getImageUrls().isEmpty()) {
                try {
                    List<String> imageUrlList = JSON.parseArray(comment.getImageUrls(), String.class);
                    commentUser.setImageUrls(imageUrlList);
                } catch (Exception e) {
                    // 解析失败时设置为空列表
                    commentUser.setImageUrls(new ArrayList<>());
                }
            } else {
                commentUser.setImageUrls(new ArrayList<>());
            }
            
            // 获取商品信息
            if (comment.getSpuId() != null) {
                Result spuResult = goodsService.findSpu(comment.getSpuId());
                if (spuResult != null && spuResult.getData() != null) {
                    SpuVO spuVO = JSON.parseObject(JSON.toJSONString(spuResult.getData()), SpuVO.class);
                    commentUser.setSpuVO(spuVO);
                    commentUser.setCreatedAt(comment.getCreatedAt());
                    commentUser.setUpdatedAt(comment.getUpdatedAt());
                }
            }
            
            commentUserList.add(commentUser);
        }
        
        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("total", resultPage.getTotal());
        result.put("pages", resultPage.getPages());
        result.put("current", resultPage.getCurrent());
        result.put("size", resultPage.getSize());
        result.put("records", commentUserList);
        
        return Result.success(result);
    }
    //更新评论状态
    @Override
    public Result updateCommentStatus(Long id, Integer status) {
        if (id == null || status == null) {
            return Result.failure(ResultCodeEnum.FAIL, "评论ID或状态不能为空");
        }
        
        Comment comment = commentMapper.selectById(id);
        if (comment == null) {
            return Result.failure(ResultCodeEnum.FAIL, "评论不存在");
        }
        
        comment.setStatus(status);
        comment.setUpdatedAt(LocalDateTime.now());
        
        commentMapper.updateById(comment);
        return Result.success("评论状态更新成功");
    }

    //删除评论
    @Override
    public Result deleteComment(Long id) {
        if (id == null) {
            return Result.failure(ResultCodeEnum.FAIL, "评论ID不能为空");
        }
        
        // 逻辑删除，将状态设为已删除(2)
        Comment comment = commentMapper.selectById(id);
        System.out.println("id: " + id);
        if (comment == null) {
            return Result.failure(ResultCodeEnum.FAIL, "评论不存在");
        }
        
        comment.setStatus(2); // 已删除状态
        comment.setUpdatedAt(LocalDateTime.now());
        
        commentMapper.updateById(comment);
        return Result.success("评论删除成功");
    }

    
} 